﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class PanelDrag : MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{
    private Vector2 originalLocalPointerPosition;
    private Vector3 originalPanelLocalPosition;
    private RectTransform panelRectTransform;
    private RectTransform parentRectTransform;
    private Vector3 offsetToOriginal;

    private void Awake()
    {
        this.panelRectTransform = this.transform.parent as RectTransform;
        if (this.panelRectTransform != null)
            this.parentRectTransform = this.panelRectTransform.parent as RectTransform;
    }

    public void OnDrag(PointerEventData data)
    {
        Vector2 localPointerPosition;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(this.parentRectTransform, data.position, data.pressEventCamera, out localPointerPosition))
        {
            this.offsetToOriginal = localPointerPosition - this.originalLocalPointerPosition;
            this.panelRectTransform.localPosition = this.originalPanelLocalPosition + this.offsetToOriginal;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        RemoteLoader.Instance.RemoteCtrl.SetCommand(new NodeMoveCommand(this.transform, this.offsetToOriginal));
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        this.originalPanelLocalPosition = this.panelRectTransform.localPosition;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(this.parentRectTransform, eventData.position, eventData.pressEventCamera, out this.originalLocalPointerPosition);
        this.transform.parent.SetAsLastSibling();
    }
}
